<?php

/**
 * {0}
 *
 * @author longpt
 * @version
 */

require_once "Abstract.php";
require_once 'DBUtils.php';

class User extends Models_Abstract
{
	/**
	 * The default table name
	 */
	protected $_name = 'users';
	protected $_primary = 'username';

	public function __construct($id, $needQuery=true)
	{
		if (!is_array($id) && !is_null($id))
		{
			$id = array('username'=>$id);
		}
		parent::__construct($id, $needQuery);
	}

	/**
	 * 
	 * Checking if the supplied username is valid (well-formed)
	 * @param unknown_type $username
	 */
	public static function IsUsernameValid($username)
	{
		$result = ctype_alnum($username);
		return $result;
	}

	/**
	 * 
	 * Check if an item is available for use.
	 * @param unknown_type $item
	 * @param unknown_type $value
	 */
	public static function CheckItemAvailability($item, $value)	{
		$user = new User(null);
		$result = $user->fetchAll(
		$user->select()
		->where("$item = :_item")
		->bind(array(':_item'=>$value))
		);
		if ($result)
		{
			$result = $result->toArray();
			if (count($result)>0)
			return false;
		}
		return true;
	}

	/**
	 * 
	 * Check if the supplied email is available
	 * @param unknown_type $email
	 */
	public static function IsEmailAvailable($email)	{
		return self::CheckItemAvailability('email', $email);
	}

	/**
	 * 
	 * Check if the supplied username is availale
	 * @param unknown_type $username
	 */
	public static function IsUsernameAvailable($username)	{
		return self::CheckItemAvailability('username', $username);
	}
	
	/**
	 * 
	 * Create an user model using an unique key in the DB
	 * @param unknown_type $key
	 * @param unknown_type $value
	 * @return the created user model 
	 * 			or null if that key value does not exist
	 */
	public static function getUserFromUniqueKey($key, $value)	{
		$user = new User(null);
		$stmt = $user->select()
		->where("$key = :_key")
		->bind(array(':_key'=>$value));
		$result = $user->fetchAll($stmt);
		$data = array();
		if ($result)
		{
			$rows = $result->toArray();
			if (count($rows)>0)
			{
				$user->setData($rows[0]);
				$user->setId(array('username'=>$user->username));
				return $user; 
			}
		}
		return null;
	}
	
	public static function getUserFromPrimaryBind($bind)	{
		return self::getUserFromUniqueKey('primary_bind', $bind);
	}

	public static function getUserFromEmail($email)	{
		return self::getUserFromUniqueKey('email', $email);
	}

	public function abstractLoad($id)
	{
		$stmt = $this->select()
		->where('username = :_usn')
		->bind(array(':_usn'=>$id['username']));
		$result = $this->getAdapter()->fetchAll($stmt, array(), Zend_Db::FETCH_OBJ);

		if (count($result)>0)
		{
			foreach($result[0] as $col=>$value){
				$this->_data[$col] = $value;
			}
		}
		else
		{
			return false;
		}
	}

	public function createDefaultData()
	{
		return array();
	}
}

